package com.suxin.plugin.intergration.factory;

import org.springframework.beans.factory.annotation.AnnotatedGenericBeanDefinition;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.GenericApplicationContext;

import java.util.function.Consumer;

/**
 * @author Tang
 * @classname SpringBeanRegister
 * @description [ spring bean 注册器 ]
 * @date 2022/7/22 23:20
 */
public class SpringBeanRegister {

    private final GenericApplicationContext applicationContext;

    public SpringBeanRegister(ApplicationContext applicationContext) {
        this.applicationContext = (GenericApplicationContext)applicationContext;
    }

    public String register(String pluginId, Class<?> aClass) {
        return register(pluginId,null, aClass);
    }

    public String register(String pluginId,String suffixName, Class<?> aClass) {
        return register(pluginId, aClass,null);
    }

    public String register(String pluginId, Class<?> aClass, Consumer<AnnotatedGenericBeanDefinition> consumer) {
        return register(pluginId, null, aClass, consumer);
    }

    public String register(String pluginId, String suffixName,Class<?> aClass,
                           Consumer<AnnotatedGenericBeanDefinition> consumer) {
        AnnotatedGenericBeanDefinition beanDefinition = new AnnotatedGenericBeanDefinition(aClass);
        PluginAnnotationBeanNameGenerator beanNameGenerator = new PluginAnnotationBeanNameGenerator(suffixName);
        String beanName = beanNameGenerator.generateBeanName(beanDefinition, applicationContext);
        if (consumer != null) {
            consumer.accept(beanDefinition);
        }
        applicationContext.registerBeanDefinition(beanName,beanDefinition);
        return beanName;
    }

}